package com.ys.zero.web;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
// java方法类
import java.lang.reflect.Method;

import javax.servlet.ServletException;
//import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

/**
 *  	/login.s   1个地址对应一个servlet
 *  	/BaseServlet/*  N个地址对应一个servlet
 *  	/BaseServlet/abc, /BaseServlet/eft  /BaseServlet
 */
// @WebServlet("/BaseServlet/*")
// 抽象类
public abstract class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		// 获取地址中的方法名
		String path = request.getRequestURL().toString();
		System.out.println(path);
		path = path.replaceAll(".+?/(\\w*)\\.s$", "$1");// 贪婪模式
		
		try {
			//执行公共代码
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=UTF-8");
			// 通过反射查找对应方法, this.getClass() 获取当前对象的类对象
			Method m = this.getClass().getDeclaredMethod(
						path, 
						HttpServletRequest.class, 
						HttpServletResponse.class);
			// 执行方法
			m.setAccessible(true); // 设置私有,受保护,默认方法可以访问
			m.invoke(this, request, response);
		} catch (NoSuchMethodException | SecurityException 
				| IllegalAccessException | IllegalArgumentException 
				| InvocationTargetException e) {
			throw new RuntimeException("方法名错误：" + path,e);
		}
	
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		doGet(request, response);
	}
	

	
	/*// /BaseServlet/login
	protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	// /BaseServlet/reg
	protected void reg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	*/
	
	/**
	 * 转json后, 使用响应对象输出
	 */
	public static void toJson(HttpServletResponse response, Object obj) throws IOException {
		String json = new Gson().toJson(obj);
		response.getWriter().append(json);
	}

}
